<template>
  <a-row id="globalheader" class="grid-demo" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        :default-selected-keys="['1']"
        @menu-item-click="doClickMenu"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '12px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../assets/sdutcm.png" />
            <div class="title">
              <img class="logo" src="../assets/sdutcm-text.png" />
            </div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <div @click="handleLogout()">
        <icon-export style="margin-right: 2px" />
        {{ store.state.user?.loginUser?.userAccount ?? "未登录" }}
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "../router/routes";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "../access/checkAccess";
import { StudentControllerService } from "../../generated";
import { message } from "ant-design-vue";

const router = useRouter();
const store = useStore();

const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.invisible) {
      return false;
    }
    // 判断登录用户是否具有权限看到此菜单
    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false;
    }
    return true;
  });
});

//默认页面
const selectedKeys = ref(["/"]);

//路由跳转后更新高亮的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

const doClickMenu = (key: string) => {
  router.push({
    path: key,
  });
};

const handleLogout = async () => {
  const res = await StudentControllerService.logoutUsingGet();
  if (res.success === true) {
    await store.dispatch("user/getLoginUser", {
      userAccount: "未登录",
      userRole: "",
    });
    sessionStorage.clear();
    router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    message.error("系统繁忙！");
  }
};
</script>
<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
  height: 40px;
}

.title-bar .logo {
  height: 40px;
}
</style>
